package com.learn.xiaoha.sqlsession.result.handle;

import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.sql.ResultSet;

/**
 * PojoResultHandle
 * pojo结果机处理器
 * @author: cyx_jay
 * @date: 2021/2/3 8:46
 */
public class  PojoResultHandle<T> implements ResultHandle<T>{


    @Override
    public T handle(ResultSet resultSet, Class t) throws Exception {
       if (resultSet.next()){
           //获取t的全部字段
           Field[] declaredFields = t.getDeclaredFields();
           if (ArrayUtils.isNotEmpty(declaredFields)){
               Object obj = t.newInstance();
               for (Field declaredField : declaredFields) {
                   declaredField.setAccessible(true);
                   declaredField.set(obj,resultSet.getObject(declaredField.getName()));
               }
               return (T) obj;
           }
       }
       return null;
    }

}

